package com.kun;

import org.junit.Test;
import redis.clients.jedis.Jedis;

//测试Redis的String类型
public class Test01_String {

    @Test
    public void testString(){
        Jedis jedis = JedisUtils.getJedis();
        jedis.flushDB(); //清空Redis数据库

        //1. 设置字符串
        jedis.set("name", "kun");
        System.out.println(jedis.get("name")); //输出：kun

        //2. 字符串追加，获取字符串长度
        jedis.append("name", "chen");
        System.out.println(jedis.strlen("name")); //返回name的值长度
        System.out.println(jedis.get("name"));

        //3. 自增自减
        jedis.set("age", "24");
        jedis.incr("age"); //age自增1，age：25
        jedis.decr("age"); //age自减1，age：24
        jedis.incrBy("age", 3); //age自增3，age：27
        jedis.decrBy("age", 3); //age自减3，age：24
        System.out.println(jedis.get("age"));

        //4.截取、替换字符串
        jedis.set("str", "hello world");
        System.out.println(jedis.getrange("str", 0, 4)); //输出：hello
        System.out.println(jedis.getrange("str", 0, -1));//输出：hello world
        jedis.setrange("str", 6, "redis"); //替换字符串，str：hello redis
        System.out.println(jedis.get("str"));

        //5.创建key，设置过期时间、非覆盖型创建
        jedis.setex("school", 15, "AnHui University");
        System.out.println(jedis.get("school")); //输出：AnHui University
        System.out.println(jedis.ttl("school"));//查看剩余时间
        jedis.setnx("school", "Beijing University");//创建key，但不覆盖已有值
        System.out.println(jedis.get("school")); //输出：AnHui University

        //6. 批量设置值
        jedis.mset("name", "kun", "age", "24", "school", "AnHui University", "str", "hello , redis");
        jedis.msetnx("name", "chen", "age", "25", "school", "Beijing University", "str", "hello world");
        System.out.println(jedis.mget("name", "age", "school", "str")); //输出：[chen, 25, Beijing University, hello world]

        //7. 对象处理
        jedis.set("person:1", "{name:kun,age:24,school:AnHui University}"); //方式1
        jedis.set("person:2:name", "kun");//方式2
        jedis.set("person:2:age", "24");
        jedis.set("person:2:school", "AnHui University");
        System.out.println(jedis.get("person:1")); //方式1
        System.out.println(jedis.mget("person:2:name", "person:2:age", "person:2:school")); //方式2

        //8. 组合命令
        System.out.println(jedis.getSet("person:1", "{name:chen,age:25,school:Beijing University}")); //获取并设置值，返回原值

        //9. 查看所有keys
        jedis.keys("*").forEach(key -> System.out.print(key+" ")); //输出所有keys

        JedisUtils.closeJedis(jedis);

    }
}
